package com.hctforgreen.greenservice.ui.adapter;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnGroupExpandListener;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import cn.dns.reader.network.Util;

import com.hctforgreen.greenservice.DownloadManagerActivityV2;
import com.hctforgreen.greenservice.R;
import com.hctforgreen.greenservice.ctr.DbController;
import com.hctforgreen.greenservice.model.BaseEntity;
import com.hctforgreen.greenservice.model.BookListEntity.BookEntity;
import com.hctforgreen.greenservice.model.SerieListEntity.ChildSerieEntity;
import com.hctforgreen.greenservice.ui.handler.AllBooksWithDbAllSeriesListHandlerV3;
import com.hctforgreen.greenservice.ui.page.AbstractDataLoaderHandler;
import com.hctforgreen.greenservice.ui.page.AbstractPageableExpandableAdapter;
import com.hctforgreen.greenservice.utils.EntryCatalogUtil;
import com.hctforgreen.greenservice.utils.FileCacheUtil;
import com.hctforgreen.greenservice.utils.HctConstants;
import com.hctforgreen.greenservice.utils.ThemeStoreUtil;
import com.hctforgreen.greenservice.utils.Utils;
import com.umeng.analytics.MobclickAgent;

/**
 * 下载列表的适配器
 * 
 * @author Tallen Zhai
 * 
 */
public class HaveDownloadBooksWithDbAllSeriesListAdapterV5 extends
		AbstractPageableExpandableAdapter<BaseEntity> implements
		OnItemClickListener {

	private static Activity mActivity;
	private ExpandableListView mListView;
	private AllBooksWithDbAllSeriesListHandlerV3 mHandler;

	/**
	 * 控制列表的展开
	 */
	private int mLastExpandPosition = -1;

	private boolean showHasDownList;// true 显示已下载列表 默认显示下载列表

	/**
	 * 
	 * @param listView
	 * @param activity
	 * @param convertView
	 * @param loadingViewResourceId
	 * @param reloadViewResourceId
	 * @param handler
	 */

	public HaveDownloadBooksWithDbAllSeriesListAdapterV5(
			ExpandableListView listView, Activity activity, View convertView,
			int loadingViewResourceId, int reloadViewResourceId,
			AbstractDataLoaderHandler<BaseEntity> handler) {
		super(listView, activity, loadingViewResourceId, reloadViewResourceId,
				handler);
		mListView = listView;
		mActivity = activity;

		mHandler = (AllBooksWithDbAllSeriesListHandlerV3) handler;
		mListView.setAdapter(this);
		mListView.setOnItemClickListener(this);
		mListView.setOnScrollListener(this);
		// mListView.setOnRefreshListener(this);
		mListView.setGroupIndicator(null);
		initGroupExpand();
		// initRefreshBtn();
	}

	public void updateBooksLayout(String downloadUrl) {

		int firstVisiblePosition = mListView.getFirstVisiblePosition();
		int lastVisiblePosition = mListView.getLastVisiblePosition();

		int visibleCount = (lastVisiblePosition - firstVisiblePosition);
		for (int i = 0; i <= visibleCount; i++) {
			View visibleView = mListView.getChildAt(i);

			if (visibleView == null) {
				continue;
			}
			LinearLayout bookLyt = (LinearLayout) visibleView
					.findViewById(R.id.lyt_book);
			if (bookLyt == null) {
				continue;
			}
			BookEntity tagBook = (BookEntity) bookLyt.getTag();
			if (tagBook != null && tagBook.download_url.equals(downloadUrl)) {

				final DbController dbController = new DbController(mActivity);
				BookEntity inDbEntity = dbController
						.getBookEntityUseBookName(tagBook.bookName);
				switchButtons(bookLyt, inDbEntity);
				initProgressBar(bookLyt, inDbEntity);
			}

		}

	}

	private void initGroupExpand() {
		mListView.setOnGroupExpandListener(new OnGroupExpandListener() {

			@Override
			public void onGroupExpand(final int groupPosition) {

				if (mLastExpandPosition == -1) {
					mListView.setSelectedGroup(groupPosition);
				} else if (mLastExpandPosition >= 0
						&& groupPosition < mLastExpandPosition) {
					mListView.collapseGroup(mLastExpandPosition);
					mListView.setSelectedGroup(groupPosition);
				} else if (groupPosition == mLastExpandPosition) {
					mListView.setSelectedGroup(groupPosition);
				} else if (mLastExpandPosition >= 0
						&& groupPosition > mLastExpandPosition) {
					mListView.collapseGroup(mLastExpandPosition);
					final Handler handler = new Handler() {
						public void handleMessage(Message msg) {
							mListView.setSelectedGroup(groupPosition);
						}
					};
					/**
					 * 延时
					 */
					new Thread() {
						public void run() {
							try {
								Thread.sleep(1000);
							} catch (Exception e) {
								e.printStackTrace();
							}
							handler.sendEmptyMessage(0);
						}
					}.start();
				}

				mLastExpandPosition = groupPosition;

			}
		});
	}

	private void updateBookZipState(final BookEntity bookEntity,
			final String state) {
		DbController dbController = new DbController(mActivity);
		bookEntity.bookZipState = state;
		dbController.updateBookZipState(bookEntity);
	}

	/**
	 * 当连接不上下载Service时的重置Db中资料的下载状态为"已取消"
	 * 
	 * @param book
	 */
	private void cancelWhenServiceUnConnection(final View bookLyt,
			final BookEntity book, final DbController dbController) {
		BookEntity inDbEntity = dbController
				.getBookEntityUseBookName(book.bookName);

		if (!inDbEntity.doWhatClick
				.equals(HctConstants.ON_ACTIVITY_KEY_DO_UPDATE_CLICK)) {
			updateBookZipState(inDbEntity,
					HctConstants.ON_ACTIVITY_KEY_BOOK_ZIP_STATE_ALREADY_CANCEL);
			switchButtons(bookLyt, inDbEntity);
		} else if (inDbEntity.doWhatClick
				.equals(HctConstants.ON_ACTIVITY_KEY_DO_UPDATE_CLICK)) {
			updateBookZipState(inDbEntity,
					HctConstants.ON_ACTIVITY_KEY_BOOK_ZIP_STATE_ANALISIS_DONE);
			switchButtons(bookLyt, inDbEntity);
		}

	}

	private void initSeriesNameTitle(ViewGroupCache viewCache,
			final ChildSerieEntity entity) {
		viewCache.getNameTv().setText(entity.seriesName);
		String sCount = mActivity.getString(R.string.child_series_count_hint);
		int iCount = (entity.childSeriesCount == -1) ? 0
				: entity.childSeriesCount;
		sCount = String.format(sCount, iCount);
		viewCache.getChildSeriesCountTv().setText(sCount);
	}

	private void inSkinLayout(ViewGroupCache viewCache,
			final ChildSerieEntity entity) {
		if (!entity.seriesName.equals("")) {
			int skinId = ThemeStoreUtil.getItemLayoutSkinId(mActivity);
			viewCache.getSerieLyt().setBackgroundResource(skinId);
			viewCache.getSerieLyt().setVisibility(View.VISIBLE);
		} else if (entity.seriesName.equals("")) {
			viewCache.getSerieLyt().setVisibility(View.GONE);
		}
		viewCache.getSerieLyt().setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
			}
		});

	}

	private void initDisplayName(final View bookLyt, BookEntity entity) {
		TextView nameTv = (TextView) bookLyt.findViewById(R.id.tv_name);
		nameTv.setText(entity.displayName);

		TextView sizeTv = (TextView) bookLyt.findViewById(R.id.tv_size);

		if (!entity.bookFileLongSize.equals("")) {
			long lBookFileLongSize = Long.valueOf(entity.bookFileLongSize);
			sizeTv.setText(FileCacheUtil.FormetFileSize(lBookFileLongSize));
		}

	}

	private void initTotalBookLayout(final View totalBookLyt,
			final ChildSerieEntity cEntity) {
		final DbController dbController = new DbController(mActivity);

		Button downloadBtn = (Button) totalBookLyt
				.findViewById(R.id.btn_download);

		Button updateBtn = (Button) totalBookLyt.findViewById(R.id.btn_update);
		/**
		 * XXX 全部下载按钮
		 */
		downloadBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				if (Utils.isWifiNetworkConnected(mActivity)) {
					downLoad(cEntity);
				} else {
					AlertDialog.Builder builder = new Builder(mActivity);
					builder.setTitle(
							mActivity
									.getString(R.string.dialog_default_title_hint))
							.setMessage(
									mActivity
											.getString(R.string.dialog_network_3g_wran))
							.setPositiveButton(
									mActivity
											.getString(R.string.dialog_confirm_hint),
									new DialogInterface.OnClickListener() {

										@Override
										public void onClick(
												DialogInterface dialog,
												int which) {
											downLoad(cEntity);
										}
									})
							.setNegativeButton(
									mActivity
											.getString(R.string.dialog_cancel_hint),
									null).create().show();
				}
			}
		});

		/**
		 * 全部更新 针对已下载可更新的书籍
		 */
		updateBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				for (int i = 0; i < cEntity.childSeriesBookIdList.size(); i++) {
					final String bookId = cEntity.childSeriesBookIdList.get(i);
					BookEntity entity = dbController.getBookEntity(bookId);
					// 可更新
					if (entity.bCanUpdate
							.equals(HctConstants.ON_ACTIVITY_KEY_BOOK_B_CAN_UPDATE_TRUE)) {
						MobclickAgent.onEvent(mActivity,
								"Account_update_download");

						entity.doWhatClick = HctConstants.ON_ACTIVITY_KEY_DO_UPDATE_CLICK;
						dbController.updateBookOnWhatClick(entity);

						/**
						 * 调用Service下载
						 */
						Util.doDownloadBook(mActivity, entity);
					}

				}

			}
		});

		updateTotalBookSize(totalBookLyt, cEntity, dbController);
	}

	private void downLoad(final ChildSerieEntity cEntity) {
		final DbController dbController = new DbController(mActivity);
		for (int i = 0; i < cEntity.childSeriesBookIdList.size(); i++) {
			final String bookId = cEntity.childSeriesBookIdList.get(i);
			BookEntity entity = dbController.getBookEntity(bookId);
			/**
			 * 未下载||下载失败||已取消||已经删除
			 */
			if (entity.bookZipState
					.equals(HctConstants.ON_ACTIVITY_KEY_BOOK_ZIP_STATE_DOWNLOAD_NONE)
					|| entity.bookZipState
							.equals(HctConstants.ON_ACTIVITY_KEY_BOOK_ZIP_STATE_DOWNLOAD_FAIL)
					|| entity.bookZipState
							.equals(HctConstants.ON_ACTIVITY_KEY_BOOK_ZIP_STATE_ALREADY_CANCEL)
					|| entity.bookZipState
							.equals(HctConstants.ON_ACTIVITY_KEY_BOOK_ZIP_STATE_ALREADY_DELETE)) {
				MobclickAgent.onEvent(mActivity, "Account_download");

				entity.doWhatClick = HctConstants.ON_ACTIVITY_KEY_DO_DOWNLOAD_CLICK;
				dbController.updateBookOnWhatClick(entity);

				/**
				 * 调用Service下载
				 */
				Util.doDownload(mActivity, entity);

			}
			/**
			 * 解析完成&&可以更新
			 */
			else if (entity.bookZipState
					.equals(HctConstants.ON_ACTIVITY_KEY_BOOK_ZIP_STATE_ANALISIS_DONE)
					&& entity.bCanUpdate
							.equals(HctConstants.ON_ACTIVITY_KEY_BOOK_B_CAN_UPDATE_TRUE)) {
				MobclickAgent.onEvent(mActivity, "Account_update_download");

				entity.doWhatClick = HctConstants.ON_ACTIVITY_KEY_DO_UPDATE_CLICK;
				dbController.updateBookOnWhatClick(entity);

				/**
				 * 调用Service下载
				 */
				Util.doDownload(mActivity, entity);
			}

		}

	}

	private void updateTotalBookSize(final View totalBookLyt,
			final ChildSerieEntity cEntity, final DbController dbController) {
		final TextView sizeTv = (TextView) totalBookLyt
				.findViewById(R.id.tv_size);
		final ProgressBar sizePb = (ProgressBar) totalBookLyt
				.findViewById(R.id.pb_size);
		sizeTv.setVisibility(View.INVISIBLE);
		sizePb.setVisibility(View.VISIBLE);
		final Handler handler = new Handler() {
			public void handleMessage(Message msg) {
				long lBookFileLongSize = (Long) msg.obj;
				sizeTv.setText(FileCacheUtil.FormetFileSize(lBookFileLongSize));
				sizeTv.setVisibility(View.VISIBLE);
				sizePb.setVisibility(View.GONE);
			}
		};
		new Thread() {
			public void run() {
				long lBookFileLongSize = 0l;
				try {

					for (int i = 0; i < cEntity.childSeriesBookIdList.size(); i++) {
						final String bookId = cEntity.childSeriesBookIdList
								.get(i);

						BookEntity inDbEntity = dbController
								.getBookEntity(bookId);
						if (inDbEntity.bookFileLongSize.equals("")) {
							continue;
						}
						lBookFileLongSize += Long
								.valueOf(inDbEntity.bookFileLongSize);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				Message message = new Message();
				message.obj = lBookFileLongSize;
				handler.sendMessage(message);

			}
		}.start();
	}

	private void initChildSerieLayout(View convertView,
			final ChildSerieEntity entity, final int position) {

		TextView nameTv = (TextView) convertView
				.findViewById(R.id.tv_child_series_name);
		nameTv.setText(entity.childSeriesName);

		if (entity.childSeriesBookIdList != null) {
			TextView countTv = (TextView) convertView
					.findViewById(R.id.tv_child_series_books_count);
			String sCount = mActivity
					.getString(R.string.child_series_books_count_hint);
			sCount = String.format(sCount, entity.childSeriesBookIdList.size());
			countTv.setText(sCount);
		}

		renderIsOff(convertView, entity, position);

	}

	private void initIsNewVisible(View convertView,
			final ChildSerieEntity entity) {

		final ImageView newIv = (ImageView) convertView
				.findViewById(R.id.iv_new);

		if (entity.childSeriesBookIdList == null) {
			newIv.setVisibility(View.GONE);
			return;
		}

		final Handler handler = new Handler() {
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case 1:
					newIv.setVisibility(View.VISIBLE);
					break;
				case 0:
					newIv.setVisibility(View.GONE);
					break;
				}

			}
		};
		new Thread() {
			public void run() {
				try {
					if (entity.childSeriesBookIdList != null) {

						for (String bookId : entity.childSeriesBookIdList) {

							DbController dbController = new DbController(
									mActivity);
							BookEntity inDbEntity = dbController
									.getBookEntity(bookId);

							if (inDbEntity.bookZipState
									.equals(HctConstants.ON_ACTIVITY_KEY_BOOK_ZIP_STATE_ANALISIS_DONE)
									&& inDbEntity.bCanUpdate
											.equals(HctConstants.ON_ACTIVITY_KEY_BOOK_B_CAN_UPDATE_TRUE)) {

								handler.sendEmptyMessage(1);
								return;
							}
						}

					}
				} catch (Exception e) {
					e.printStackTrace();
				}

				handler.sendEmptyMessage(0);

			}
		}.start();
	}

	private void renderIsOff(final View convertView,
			final ChildSerieEntity entity, final int position) {
		FrameLayout childSerieHeaderLyt = (FrameLayout) convertView
				.findViewById(R.id.lyt_child_serie_header);
		if (entity.childSeriesCount == -1) {
			childSerieHeaderLyt.setVisibility(View.GONE);
		} else if (entity.childSeriesCount != -1) {
			childSerieHeaderLyt.setVisibility(View.VISIBLE);
		}

	}

	private void initButtons(final View bookLyt, final BookEntity entity) {
		final DbController dbController = new DbController(mActivity);
		/**
		 * 下载
		 */
		Button downloadBtn = (Button) bookLyt.findViewById(R.id.btn_download);
		downloadBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				MobclickAgent.onEvent(mActivity, "Account_download");

				entity.doWhatClick = HctConstants.ON_ACTIVITY_KEY_DO_DOWNLOAD_CLICK;
				dbController.updateBookOnWhatClick(entity);

				/**
				 * 调用Service下载
				 */
				Util.doDownloadBook(mActivity, entity);
			}
		});
		/**
		 * 取消
		 */
		Button cancelBtn = (Button) bookLyt.findViewById(R.id.btn_cancel);
		cancelBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				MobclickAgent.onEvent(mActivity, "Account_cancel_download");

				cancelWhenServiceUnConnection(bookLyt, entity, dbController);

				((DownloadManagerActivityV2) mActivity).getConnection()
						.cancelDownloadingUrl(entity.download_url);

			}
		});
		/**
		 * 更新
		 */
		Button updateBtn = (Button) bookLyt.findViewById(R.id.btn_update);
		updateBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				MobclickAgent.onEvent(mActivity, "Account_update_download");

				entity.doWhatClick = HctConstants.ON_ACTIVITY_KEY_DO_UPDATE_CLICK;
				dbController.updateBookOnWhatClick(entity);

				/**
				 * 调用Service下载
				 */
				Util.doDownloadBook(mActivity, entity);
			}
		});
		/**
		 * 删除
		 */
		Button deleteBtn = (Button) bookLyt.findViewById(R.id.btn_delete);
		deleteBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				MobclickAgent.onEvent(mActivity, "Account_delete_download");
				entity.bookZipState = HctConstants.ON_ACTIVITY_KEY_BOOK_ZIP_STATE_ALREADY_DELETE;
				DbController dbController = new DbController(mActivity);
				dbController.updateBookZipState(entity);

				Util.tryToDeleteBook(entity, mActivity);
				// mSelf.notifyDataSetChanged();
				switchButtons(bookLyt, entity);
			}
		});
		/**
		 * 解析中
		 */
		Button analysisBtn = (Button) bookLyt.findViewById(R.id.btn_analysis);
		analysisBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (!((DownloadManagerActivityV2) mActivity).getConnection()
						.isBeingDownloaded(entity.download_url)
						&& !entity.doWhatClick
								.equals(HctConstants.ON_ACTIVITY_KEY_DO_UPDATE_CLICK)) {

					updateBookZipState(
							entity,
							HctConstants.ON_ACTIVITY_KEY_BOOK_ZIP_STATE_ALREADY_CANCEL);
					switchButtons(bookLyt, entity);
				} else if (!((DownloadManagerActivityV2) mActivity)
						.getConnection().isBeingDownloaded(entity.download_url)
						&& entity.doWhatClick
								.equals(HctConstants.ON_ACTIVITY_KEY_DO_UPDATE_CLICK)) {

					updateBookZipState(
							entity,
							HctConstants.ON_ACTIVITY_KEY_BOOK_ZIP_STATE_ANALISIS_DONE);
					switchButtons(bookLyt, entity);
				}
			}
		});

	}

	private void switchButtons(final View bookLyt, BookEntity entity) {
		/**
		 * 进度条
		 */
		ProgressBar oneBookPb = (ProgressBar) bookLyt
				.findViewById(R.id.pb_download);
		/**
		 * 下载
		 */
		Button downloadBtn = (Button) bookLyt.findViewById(R.id.btn_download);
		/**
		 * 取消
		 */
		Button cancelBtn = (Button) bookLyt.findViewById(R.id.btn_cancel);
		/**
		 * 已完成
		 */
		TextView doneTv = (TextView) bookLyt
				.findViewById(R.id.tv_download_done);
		/**
		 * 解析中
		 */
		Button analysisBtn = (Button) bookLyt.findViewById(R.id.btn_analysis);
		/**
		 * 更新
		 */
		Button updateBtn = (Button) bookLyt.findViewById(R.id.btn_update);

		/**
		 * 删除
		 */
		Button deleteBtn = (Button) bookLyt.findViewById(R.id.btn_delete);
		/**
		 * 有更新包%1$s）
		 */
		TextView hasUpdateZipTv = (TextView) bookLyt
				.findViewById(R.id.tv_has_update_zip);

		/**
		 * 已经下载的size
		 */
		TextView downloadedSizeTv = (TextView) bookLyt
				.findViewById(R.id.tv_downloaded_size);

		TextView sizeHeaderTv = (TextView) bookLyt
				.findViewById(R.id.tv_size_header);
		/**
		 * 等待下载
		 */
		TextView waitingTv = (TextView) bookLyt
				.findViewById(R.id.tv_download_waiting);

		/**
		 * 未下载 、下载失败
		 */
		if (entity.bookZipState
				.equals(HctConstants.ON_ACTIVITY_KEY_BOOK_ZIP_STATE_DOWNLOAD_NONE)
				|| entity.bookZipState
						.equals(HctConstants.ON_ACTIVITY_KEY_BOOK_ZIP_STATE_DOWNLOAD_FAIL)) {
			oneBookPb.setVisibility(View.GONE);
			downloadBtn.setVisibility(View.VISIBLE);
			cancelBtn.setVisibility(View.GONE);
			doneTv.setVisibility(View.GONE);
			analysisBtn.setVisibility(View.GONE);
			updateBtn.setVisibility(View.GONE);
			deleteBtn.setVisibility(View.GONE);

			hasUpdateZipTv.setVisibility(View.GONE);
			downloadedSizeTv.setVisibility(View.GONE);
			sizeHeaderTv.setVisibility(View.GONE);

			waitingTv.setVisibility(View.GONE);
		}
		/**
		 * 正在下载
		 */
		else if (entity.bookZipState
				.equals(HctConstants.ON_ACTIVITY_KEY_BOOK_ZIP_STATE_DOWNLOAD_ING)) {
			oneBookPb.setVisibility(View.VISIBLE);
			downloadBtn.setVisibility(View.GONE);
			cancelBtn.setVisibility(View.VISIBLE);
			doneTv.setVisibility(View.GONE);
			analysisBtn.setVisibility(View.GONE);
			updateBtn.setVisibility(View.GONE);
			deleteBtn.setVisibility(View.GONE);

			hasUpdateZipTv.setVisibility(View.GONE);
			downloadedSizeTv.setVisibility(View.VISIBLE);
			sizeHeaderTv.setVisibility(View.VISIBLE);

			waitingTv.setVisibility(View.GONE);
		}
		/**
		 * 已取消
		 */
		else if (entity.bookZipState
				.equals(HctConstants.ON_ACTIVITY_KEY_BOOK_ZIP_STATE_ALREADY_CANCEL)) {
			oneBookPb.setVisibility(View.GONE);
			downloadBtn.setVisibility(View.VISIBLE);
			cancelBtn.setVisibility(View.GONE);
			doneTv.setVisibility(View.GONE);
			analysisBtn.setVisibility(View.GONE);
			updateBtn.setVisibility(View.GONE);
			deleteBtn.setVisibility(View.GONE);

			hasUpdateZipTv.setVisibility(View.GONE);
			downloadedSizeTv.setVisibility(View.GONE);
			sizeHeaderTv.setVisibility(View.GONE);

			waitingTv.setVisibility(View.GONE);
		}
		/**
		 * 下载完成
		 */
		else if (entity.bookZipState
				.equals(HctConstants.ON_ACTIVITY_KEY_BOOK_ZIP_STATE_DOWNLOAD_DONE)) {
			oneBookPb.setVisibility(View.GONE);
			downloadBtn.setVisibility(View.GONE);
			cancelBtn.setVisibility(View.GONE);
			doneTv.setVisibility(View.VISIBLE);
			analysisBtn.setVisibility(View.GONE);
			updateBtn.setVisibility(View.GONE);
			deleteBtn.setVisibility(View.GONE);

			hasUpdateZipTv.setVisibility(View.GONE);
			downloadedSizeTv.setVisibility(View.GONE);
			sizeHeaderTv.setVisibility(View.GONE);

			waitingTv.setVisibility(View.GONE);
		}
		/**
		 * 正在解析
		 */
		else if (entity.bookZipState
				.equals(HctConstants.ON_ACTIVITY_KEY_BOOK_ZIP_STATE_ANALISIS_ING)) {
			oneBookPb.setVisibility(View.GONE);
			downloadBtn.setVisibility(View.GONE);
			cancelBtn.setVisibility(View.GONE);
			doneTv.setVisibility(View.VISIBLE);
			analysisBtn.setVisibility(View.VISIBLE);
			updateBtn.setVisibility(View.GONE);
			deleteBtn.setVisibility(View.GONE);

			hasUpdateZipTv.setVisibility(View.GONE);
			downloadedSizeTv.setVisibility(View.GONE);
			sizeHeaderTv.setVisibility(View.GONE);

			waitingTv.setVisibility(View.GONE);
		}
		/**
		 * 解析完成
		 */
		else if (entity.bookZipState
				.equals(HctConstants.ON_ACTIVITY_KEY_BOOK_ZIP_STATE_ANALISIS_DONE)) {
			oneBookPb.setVisibility(View.GONE);
			downloadBtn.setVisibility(View.GONE);
			cancelBtn.setVisibility(View.GONE);

			analysisBtn.setVisibility(View.GONE);

			downloadedSizeTv.setVisibility(View.GONE);
			sizeHeaderTv.setVisibility(View.GONE);

			waitingTv.setVisibility(View.GONE);

			if (entity.bCanUpdate
					.equals(HctConstants.ON_ACTIVITY_KEY_BOOK_B_CAN_UPDATE_TRUE)) {
				doneTv.setVisibility(View.GONE);

				deleteBtn.setVisibility(View.VISIBLE);
				updateBtn.setVisibility(View.VISIBLE);

				hasUpdateZipTv.setVisibility(View.VISIBLE);

				renderUpdateZipSize(entity, bookLyt);

			} else if (entity.bCanUpdate
					.equals(HctConstants.ON_ACTIVITY_KEY_BOOK_B_CAN_UPDATE_FALSE)) {
				doneTv.setVisibility(View.VISIBLE);

				deleteBtn.setVisibility(View.VISIBLE);
				updateBtn.setVisibility(View.GONE);

				hasUpdateZipTv.setVisibility(View.GONE);

			}
		}
		/**
		 * 已经删除
		 */
		else if (entity.bookZipState
				.equals(HctConstants.ON_ACTIVITY_KEY_BOOK_ZIP_STATE_ALREADY_DELETE)) {
			oneBookPb.setVisibility(View.GONE);
			downloadBtn.setVisibility(View.VISIBLE);
			cancelBtn.setVisibility(View.GONE);
			doneTv.setVisibility(View.GONE);
			analysisBtn.setVisibility(View.GONE);
			updateBtn.setVisibility(View.GONE);
			deleteBtn.setVisibility(View.GONE);

			hasUpdateZipTv.setVisibility(View.GONE);
			downloadedSizeTv.setVisibility(View.GONE);
			sizeHeaderTv.setVisibility(View.GONE);

			waitingTv.setVisibility(View.GONE);
		}
		/**
		 * 等待下载
		 */
		else if (entity.bookZipState
				.equals(HctConstants.ON_ACTIVITY_KEY_BOOK_ZIP_STATE_DOWNLOAD_WAITING)) {
			oneBookPb.setVisibility(View.GONE);
			downloadBtn.setVisibility(View.GONE);
			cancelBtn.setVisibility(View.VISIBLE);
			doneTv.setVisibility(View.GONE);
			analysisBtn.setVisibility(View.GONE);
			updateBtn.setVisibility(View.GONE);
			deleteBtn.setVisibility(View.GONE);

			hasUpdateZipTv.setVisibility(View.GONE);
			downloadedSizeTv.setVisibility(View.GONE);
			sizeHeaderTv.setVisibility(View.GONE);

			waitingTv.setVisibility(View.VISIBLE);
		}
	}

	private void renderUpdateZipSize(BookEntity entity, final View bookLyt) {
		final TextView hasUpdateZipTv = (TextView) bookLyt
				.findViewById(R.id.tv_has_update_zip);
		String sUpdateZipSize = mActivity
				.getString(R.string.has_update_zip_hint);

		if (!entity.bookFileLongSize.equals("")) {
			long lBookFileLongSize = Long.valueOf(entity.bookFileLongSize);
			sUpdateZipSize = String.format(sUpdateZipSize,
					FileCacheUtil.FormetFileSize(lBookFileLongSize));
			hasUpdateZipTv.setText(sUpdateZipSize);
		}

		final TextView sizeTv = (TextView) bookLyt.findViewById(R.id.tv_size);

		try {
			long lCurrentBookFileLongSize = Long
					.valueOf(entity.currentBookFileLongSize);
			sizeTv.setText(FileCacheUtil
					.FormetFileSize(lCurrentBookFileLongSize));
		} catch (Exception e) {
		}

	}

	private void initProgressBar(final View bookLyt, BookEntity entity) {
		if (entity.progress == 99 || entity.progress == 100) {
			return;
		}

		/**
		 * 进度条
		 */
		ProgressBar oneBookPb = (ProgressBar) bookLyt
				.findViewById(R.id.pb_download);
		TextView downloadedSizeTv = (TextView) bookLyt
				.findViewById(R.id.tv_downloaded_size);
		/**
		 * 不等于空说明已下载完
		 */
		if (entity.progress < 100 && entity.progress != 0) {

			oneBookPb.setProgress(entity.progress);

			renderDownloadedSize(entity, downloadedSizeTv);
		} else if (entity.progress == 100) {
			oneBookPb.setProgress(entity.progress);

		}

	}

	/**
	 * 
	 * @param entity
	 * @param downloadedSizeTv
	 */
	private void renderDownloadedSize(BookEntity entity,
			TextView downloadedSizeTv) {
		String sUnit = entity.bookFileSize.substring(
				entity.bookFileSize.length() - 1, entity.bookFileSize.length());
		String sAllSize = entity.bookFileSize.substring(0,
				entity.bookFileSize.length() - 1);

		String sDownloadedSize = "%1$.2f" + sUnit;
		sDownloadedSize = String.format(sDownloadedSize,
				Float.valueOf(sAllSize) * entity.progress / 100);

		downloadedSizeTv.setText(sDownloadedSize);

	}

	class ViewGroupCache {
		private View baseView;
		private LinearLayout firstLyt;
		private TextView nameTv;
		private TextView childSeriesCountTv;

		private TextView childSeriesNameTv;
		private ImageView newIv;
		private TextView childSeriesBooksCountTv;
		private ImageView switchIv;

		private View rootLyt;

		public ViewGroupCache(View view) {
			baseView = view;
		}

		public View getRootLyt() {
			if (rootLyt == null) {
				rootLyt = (LinearLayout) baseView.findViewById(R.id.lyt_root);
			}
			return rootLyt;
		}

		public LinearLayout getSerieLyt() {
			if (firstLyt == null) {
				firstLyt = (LinearLayout) baseView
						.findViewById(R.id.lyt_series);
			}
			return firstLyt;
		}

		public TextView getNameTv() {
			if (nameTv == null) {
				nameTv = (TextView) baseView.findViewById(R.id.tv_name);
			}
			return nameTv;
		}

		public TextView getChildSeriesCountTv() {
			if (childSeriesCountTv == null) {
				childSeriesCountTv = (TextView) baseView
						.findViewById(R.id.tv_child_series_count);
			}
			return childSeriesCountTv;
		}

		public TextView getChildSeriesNameTv() {
			if (childSeriesNameTv == null) {
				childSeriesNameTv = (TextView) baseView
						.findViewById(R.id.tv_child_series_name);
			}
			return childSeriesNameTv;
		}

		public ImageView getNewIv() {
			if (newIv == null) {
				newIv = (ImageView) baseView.findViewById(R.id.iv_new);
			}
			return newIv;
		}

		public TextView getChildSeriesBooksCountTv() {
			if (childSeriesBooksCountTv == null) {
				childSeriesBooksCountTv = (TextView) baseView
						.findViewById(R.id.tv_child_series_books_count);
			}
			return childSeriesBooksCountTv;
		}

		public ImageView getSwitchTv() {
			if (switchIv == null) {
				switchIv = (ImageView) baseView.findViewById(R.id.iv_switch);
			}
			return switchIv;
		}
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {

	}

	@Override
	public void refreshTop(ArrayList<BaseEntity> values) {

	}

	@Override
	public int getChildrenCount(int groupPosition) {
		return ((ChildSerieEntity) getGroup(groupPosition)).childSeriesBookIdList
				.size() + 1;
	}

	@Override
	public Object getChild(int groupPosition, int childPosition) {

		return ((ChildSerieEntity) getGroup(groupPosition)).childSeriesBookIdList
				.get(childPosition - 1);
	}

	@Override
	public long getChildId(int groupPosition, int childPosition) {
		return childPosition;
	}

	@Override
	public boolean hasStableIds() {
		return true;
	}

	@Override
	public boolean isChildSelectable(int groupPosition, int childPosition) {
		return true;
	}

	@Override
	public int getChildType(int groupPosition, int childPosition) {
		if (childPosition == 0) {
			return 0;
		} else {
			return 1;
		}
	}

	@Override
	public int getChildTypeCount() {
		return 2;
	}

	@Override
	public View getGroupView(int groupPosition, boolean isExpanded,
			View convertView, ViewGroup parent) {
		ViewGroupCache viewCache;
		final ChildSerieEntity entity = (ChildSerieEntity) getGroup(groupPosition);
		if (convertView == null) {
			convertView = View.inflate(mActivity,
					R.layout.item_download_level_1_child_serie_lst, null);
			viewCache = new ViewGroupCache(convertView);
			convertView.setTag(viewCache);

		} else {
			viewCache = (ViewGroupCache) convertView.getTag();
		}
		inSkinLayout(viewCache, entity);
		initSeriesNameTitle(viewCache, entity);

		initChildSerieLayout(viewCache.getRootLyt(), entity, groupPosition);

		initIsNewVisible(convertView, entity);
		initSwitchTv(isExpanded, viewCache);
		return convertView;
	}

	private void initSwitchTv(boolean isExpanded, ViewGroupCache viewCache) {
		if (!isExpanded) {
			viewCache.getSwitchTv().setBackgroundResource(R.drawable.ic_off);
		} else if (isExpanded) {
			viewCache.getSwitchTv().setBackgroundResource(R.drawable.ic_on);
		}
	}

	@Override
	public View getChildView(int groupPosition, int childPosition,
			boolean isLastChild, View convertView, ViewGroup parent) {

		int type = getChildType(groupPosition, childPosition);
		ViewChildCache viewCache;
		if (convertView == null) {

			switch (type) {
			case 0:
				convertView = View.inflate(mActivity,
						R.layout.item_download_total_book_lst, null);
				viewCache = new ViewChildCache(convertView);
				convertView.setTag(viewCache);

				break;

			default:
				convertView = View.inflate(mActivity,
						R.layout.item_download_book_lst, null);
				viewCache = new ViewChildCache(convertView);

				convertView.setTag(viewCache);

				break;
			}
		} else {
			viewCache = (ViewChildCache) convertView.getTag();
		}
		switch (type) {
		case 0:
			ChildSerieEntity childSerieEntity = (ChildSerieEntity) getGroup(groupPosition);
			initTotalBookLayout(viewCache.getRootLyt(), childSerieEntity);
			break;
		default:

			final BookEntity entity = getDbBookEntity(groupPosition,
					childPosition);
			viewCache.getBookLyt().setTag(entity);

			viewCache.getBookLyt().setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					EntryCatalogUtil catalogUtil = new EntryCatalogUtil();
					try {
						if (!catalogUtil.startEntryCatalogActivity(mActivity,
								entity, false)) {
							// 没下载不知道该干嘛，提示？
							notifyDataSetChanged();// 说明文件可能不存在，需重新下载
						}
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			});
			initDisplayName(viewCache.getRootLyt(), entity);

			switchButtons(viewCache.getRootLyt(), entity);
			initProgressBar(viewCache.getRootLyt(), entity);

			initButtons(viewCache.getRootLyt(), entity);

			break;
		}

		return convertView;
	}

	private BookEntity getDbBookEntity(int groupPosition, int childPosition) {
		final String bookId = (String) getChild(groupPosition, childPosition);
		DbController dbController = new DbController(mActivity);
		BookEntity entity = dbController.getBookEntity(bookId);
		return entity;
	}

	class ViewChildCache {
		private View baseView;
		private LinearLayout rootLyt;
		private LinearLayout bookLyt;

		public ViewChildCache(View view) {
			baseView = view;
		}

		public View getRootLyt() {
			if (rootLyt == null) {
				rootLyt = (LinearLayout) baseView.findViewById(R.id.lyt_root);
			}
			return rootLyt;
		}

		public View getBookLyt() {
			if (bookLyt == null) {
				bookLyt = (LinearLayout) baseView.findViewById(R.id.lyt_book);
			}
			return bookLyt;
		}
	}

	public void notifyDataSetChanged(boolean showList) {

		// List<ChildSerieEntity> baseEntities = (List<ChildSerieEntity>)
		// getmList();

		super.notifyDataSetChanged();
	}
}
